package com.icesoft.base.manager.dao.impl;

import com.icesoft.base.manager.dao.IDataScopeFilter;
import com.icesoft.base.manager.entity.security.RelSysRoleOrg;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.entity.manager.RelSysOrgOwner;
import com.icesoft.core.dao.criteria.FromBuilder;
import com.icesoft.core.dao.criteria.PropertyFilter;

import java.util.List;

public class OrgQueryScopeFilter implements IDataScopeFilter {

    private FromBuilder fromBuilder;
    private PropertyFilter propertyFilter;
    private int userOrgCompanyId;
    private int userOrgId;
    private int userOrgPid;

    public OrgQueryScopeFilter(FromBuilder fromBuilder, SysOrg userOrg) {
        this.fromBuilder = fromBuilder;
        this.propertyFilter = fromBuilder.where().andFilter();
        this.userOrgId = userOrg.getId();
        this.userOrgPid = userOrg.getPid();
        this.userOrgCompanyId = userOrg.getCompanyId();
        fromBuilder.distinct();
    }

    @Override
    public void scopeCustom(List<Integer> customRoleIds) {
        fromBuilder.join(RelSysRoleOrg.class, "r").on("r.orgId", "id");
        propertyFilter.orIn("r.roleId", customRoleIds);
    }

    @Override
    public void scopeOrgOwnerCustom() {
        fromBuilder.join(RelSysOrgOwner.class, "n").on("n.ownerOrgId", "id");
        propertyFilter.orEq("n.orgId", userOrgId);
    }

    @Override
    public void scopeOwnChildOne() {
        propertyFilter.orEq("id", userOrgId).orEq("pid", userOrgId);
    }

    @Override
    public void scopeOwnLevel() {
        propertyFilter.orEq("pid", userOrgPid);
    }

    @Override
    public void scopeOwnCompany() {
        propertyFilter.andEq("companyId", userOrgCompanyId);
    }

    @Override
    public void scopeOwn() {
        propertyFilter.orEq("id", userOrgId);
    }
}
